package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.enums.TaskTypeEnum;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import com.zxc.apis.schedule.IScheduleClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Resource
    private IScheduleClient scheduleClient;
    @Resource
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Resource
    private WmNewsMapper wmNewsMapper;

    @Override
    @Async
    public void addNewsToTask(Integer id, LocalDateTime publishTime) {
        Task task = new Task();
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setExecuteTime(publishTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        scheduleClient.addTask(task);
    }

    @Scheduled(fixedRate = 1000)
    @Override
    public void scanNewsByTask() {
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (responseResult.getCode().equals(200) && responseResult.getData() != null) {

            Task task = JSON.parseObject(JSON.toJSONString(responseResult.getData()), Task.class);
            byte[] parameters = task.getParameters();

            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            wmNews = wmNewsMapper.selectById(wmNews);
            wmNewsAutoScanService.autoScanWmNews(wmNews);
        }
    }
}
